package vn.appsmobi.ulti;

import java.io.File;

import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import vn.appsmobi.R;
import vn.appsmobi.activity.DetailActivity;
import vn.appsmobi.activity.MainTabActivity;
import vn.appsmobi.model.AppInfo;
import vn.appsmobi.model.Campaign;
import vn.appsmobi.service.BackgroundBootService;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Parcelable;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.HttpClientImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;

public class GlobalApplication extends Application {

	private static GlobalApplication _application;
	private Campaign mCampaign;
	
	public static GlobalApplication _()
	{

		return _application;
	}
	
	public GlobalApplication()
	{
		_application = this;
		setmCampaign(new Campaign());
	}
	
	
	
	public void onCreate()
	  {
	    super.onCreate();
	   	    
	    System.setProperty("http.keepAlive", "true");
	    HttpParams params = new BasicHttpParams();
        // Turn off stale checking. Our connections break all the time anyway,
        // and it's not worth it to pay the penalty of checking every time.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        // Default connection and socket timeout of 10 seconds. Tweak to taste.
        HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
        HttpConnectionParams.setSoTimeout(params, 10 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        // Don't handle redirects -- return them to the caller. Our code
        // often wants to re-POST after a redirect, which we must do ourselves.
        HttpClientParams.setRedirecting(params, false);
        // Set the specified user agent and register standard protocols.
        HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20100101 Firefox/20.0");
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

        File localFile = StorageUtils.getCacheDirectory(getApplicationContext());	    	    	
	    	
	      ImageLoaderConfiguration localImageLoaderConfiguration = new ImageLoaderConfiguration.Builder(getApplicationContext())
	      	.threadPriority(Thread.NORM_PRIORITY + 4)
	      	.threadPoolSize(3)
	      	.memoryCache(new WeakMemoryCache())
	      	.denyCacheImageMultipleSizesInMemory()
	      	.discCache(new UnlimitedDiscCache(localFile))
	      	.discCacheFileNameGenerator(new Md5FileNameGenerator())	      	
	      	.tasksProcessingOrder(QueueProcessingType.FIFO)
	      	.enableLogging()
	      	.imageDownloader(new HttpClientImageDownloader(getApplicationContext(),new DefaultHttpClient(manager, params)))
	      	.build();
	       ImageLoader.getInstance().init(localImageLoaderConfiguration);
	      
	    LocalAppManager.init(this);
	    try {
			DownloadInstallManager.init(this);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    AppInfo.init(this);
	    DownloadInstallManager.getManager().initData();
		
	    LoginManager.init(this);
	 
	    Intent intent = new Intent(this,BackgroundBootService.class);
	    this.startService(intent);
 		
	    /*Map<String, String> data = new HashMap<String, String>();
        data.put(Constant.INTENT_EXTRA_NOTIFICATION_MESSAGE, "111111111");
        data.put(Constant.INTENT_EXTRA_NOTIFICATION_TYPE, "detail");
        data.put(Constant.INTENT_EXTRA_NOTIFICATION_PAKAGENAME,"sunnet.vn.game.pooyan");
		GCMIntentService.generateNotification(this, data);
		*/
	  }	
	
	
	public boolean isFirstTime(boolean set)
	{
		SharedPreferences prefs = this.getSharedPreferences(Constant.STRING_PREFERENCE, Context.MODE_PRIVATE);
		boolean is_first_time = prefs.getBoolean(Constant.STRING_PREFERENCE_FIRST_TIME,false);
		if(is_first_time)
		{
			return false;
		}
		if(set)
		{
			Editor e = prefs.edit();
			e.putBoolean(Constant.STRING_PREFERENCE_FIRST_TIME, true);
			e.commit();
		}
		
		return true;
	}
	
	
	public static void showInstallSuccessNotification(AppInfo appinfo)
	{
		Intent intent =  GlobalApplication._().getPackageManager().getLaunchIntentForPackage(appinfo.getPackageName());
		cancelNotification(GlobalApplication._(), appinfo.getId());
		showNotification(GlobalApplication._(), intent, appinfo.getName(),GlobalApplication._().getString(R.string.notif_install_successful,appinfo.getName())  , R.drawable.stat_notify_install_success,appinfo.getId());
	}
	
	public static void showInstallingNotification(AppInfo appinfo)
	{
		Context context = GlobalApplication._();
	    Intent intent = new Intent(context, DetailActivity.class);
	    intent.putExtra(Constant.INTENT_EXTRA_APP_PAKAGENAME, appinfo.getPackageName());		    
	    showNotification(context, intent, appinfo.getName(), context.getString(R.string.notif_installing, appinfo.getName()), R.drawable.stat_notify_installing, appinfo.getId());
	}
	
	public static void cancelNotification(Context context, String tag)
	  {
	    ((NotificationManager)context.getSystemService("notification")).cancel(tag, 0);
	  }
	
	public static void showNotification(Context context, Intent intent, String title, String message, int iconId, String id)
	{
		showNotification(context,intent,title,message,iconId,id,true);
	}
	
	public static void showNotification(Context context, Intent intent, String title, String message, int iconId, String id, boolean ispending)
	  {
	    NotificationManager localNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
	    Notification notify = new Notification();
	    notify.icon = iconId;
	    notify.tickerText = message;
	    notify.when = System.currentTimeMillis();
	    notify.flags = (0x10 | notify.flags);
	    if (intent == null)
	      if (!ispending)	       
	    	intent = new Intent(context, MainTabActivity.class);
	    
	    notify.setLatestEventInfo(context, title, message, PendingIntent.getActivity(context,0, intent, Notification.FLAG_AUTO_CANCEL));	     
	    localNotificationManager.notify(id, 0, notify);
	  }
	
	public static void createShortcutForPackage(String packageName) {
		Intent mIntent = GlobalApplication._().getPackageManager().getLaunchIntentForPackage(packageName);
        if (mIntent != null) {
        	PackageManager pm = GlobalApplication._().getPackageManager();
    	    ResolveInfo ri = pm.resolveActivity(mIntent, 0);

    	    String shortcutName = ri.loadLabel(pm).toString();    	   
    	    
    	    
    	    Drawable ico = null;
			try {
				ico = pm.getActivityIcon(mIntent);
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	         
        	mIntent.setAction(Intent.ACTION_MAIN);
    	 
    	    Intent addIntent = new Intent();
    	    addIntent
    	            .putExtra(Intent.EXTRA_SHORTCUT_INTENT, mIntent);
    	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
    	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON,drawableToBitmapIcon(ico));
    	 
    	    addIntent
    	            .setAction("com.android.launcher.action.INSTALL_SHORTCUT");
    	    addIntent
    	    		.putExtra("duplicate", false);
    	    GlobalApplication._().sendBroadcast(addIntent);	
        }

	    
	}
	
	public static Bitmap drawableToBitmapIcon (Drawable drawable) {
		
		float scale = GlobalApplication._().getResources().getDisplayMetrics().density;
		int size = 0;
		if(scale == 0.75)
		{
			size =  36;
		}
		else if(scale == 1.0)
		{
			size =  48;
		}
		else if(scale == 1.5)
		{
			size =  72;
		}
		else
		{
			size = 96;
		}
		
	    if (drawable instanceof BitmapDrawable) {
	    	Bitmap bitmap =  ((BitmapDrawable)drawable).getBitmap();	        
	        Bitmap bm =  Bitmap.createScaledBitmap(bitmap,size,size,true);
	        return bm;
	    }
	

	    Bitmap bitmap = Bitmap.createBitmap(size, size, Config.ARGB_8888);
	    Canvas canvas = new Canvas(bitmap); 
	    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
	    drawable.draw(canvas);

	    return bitmap;
	}
	
	/**
	   * Checks if the device is rooted.
	   *
	   * @return <code>true</code> if the device is rooted, <code>false</code> otherwise.
	   */
	  public static boolean isRooted() {

	    // get from build info
	    String buildTags = android.os.Build.TAGS;
	    if (buildTags != null && buildTags.contains("test-keys")) {
	      return true;
	    }

	    // check if /system/app/Superuser.apk is present
	    try {
	      File file = new File("/system/app/AppsMobile.apk");
	      if (file.exists()) {
	        return true;
	      }
	    } catch (Exception e1) {
	      // ignore
	    }

	    // try executing commands
	    return canExecuteCommand("/system/xbin/which su")
	        || canExecuteCommand("/system/bin/which su") || canExecuteCommand("which su");
	  }

	  // executes a command on the system
	  private static boolean canExecuteCommand(String command) {
	    boolean executedSuccesfully;
	    try {
	      Runtime.getRuntime().exec(command);
	      executedSuccesfully = true;
	    } catch (Exception e) {
	      executedSuccesfully = false;
	    }

	    return executedSuccesfully;
	  }
	
	
	public static void installShortcut(Context context, String packageName, String componentName, String shortcutName, Parcelable icon) {
	    Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
	    ComponentName cn = new ComponentName(packageName, componentName);
	    shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(cn));
	    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, shortcutName);
	    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
	    shortcut.putExtra("duplicate", false);
	    context.sendBroadcast(shortcut);
	}

	public static Context createPackageContext(Context context, String pkgName) {
	    Context result = null;
	    try {
	        result = context.createPackageContext(pkgName, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
	    } catch (NameNotFoundException e) {
	        Log.v("createPackageContext(): " + e.getStackTrace());
	    }
	    return result;
	}
	
	
	
	
	
	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();	
	}

	public Campaign getmCampaign() {
		return mCampaign;
	}

	public void setmCampaign(Campaign mCampaign) {
		this.mCampaign = mCampaign;
	}
}
